from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from question.models import SoftwareQuestion,QuestionHandle
from software.models import Software,SoftwareVersion
from log.models import UserLog
from announcement.views.views_anno import createAnnouncement,announcementCreate
import pdb,os

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()

def addQuestion(request, *args, **kwargs):
    """
        url    : /question/raise/
        method : POST

    :param request:
            token:data.token,//token
            softwareVersionId:data.softwareVersionId,//软件版本id
            title:data.title,
            questionContent:data.questionContent,//问题内容

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType
    softwareVersion = SoftwareVersion.objects.get(pk=requestParam['softwareVersionId'])

    if userType == '3':
        question = SoftwareQuestion.objects.create(
            user=user,
            softwareVersion=softwareVersion,
            title=requestParam['title'],
            questionContent=requestParam['questionContent'], 
        ) 
        announcementCreate(
            type='question',
            num='1',
            userType='12',
            userId=user.id,
            softwareVersionId=question.softwareVersion.id,
            IdNum=question.id
        )
        # pdb.set_trace()
        option = '提出了' + str(question.title) + '问题' 
        userIP = datacheck.getIP(request)
        log = UserLog.objects.create(
            user=user,
            userIP=userIP,
            operate=option,
        )
    
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)
    
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def questionOption(request, *args, **kwargs):
    """
        url    : /question/option/
        method : POST

    :param request:
            token:data.token,//token
            questionId:data.questionId,//问题ID
            operation:data.operation,//0：处理，1:删除、3：恢复
            handleContent:data.handleContent,//解决方案

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType
    
    question = SoftwareQuestion.objects.get(pk=requestParam['questionId'])
        
    if requestParam['operation'] == '0':
        if userType == '1' or userType == '2':   
            handle = QuestionHandle.objects.create(
                user=user,
                question=question,
                handleContent=requestParam['handleContent'], 
            )
            question.ishandle = True
            question.questionState = 1          
            question.save()
            announcementCreate(
                type='question',
                num='2',
                userType='123',
                userId=user.id,
                softwareVersionId=question.softwareVersion.id,
                IdNum=question.id
            ) 
            option = '回复了' + str(question.title) + '问题'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )      
        else:
            data = {
                'code': 1,
                'msg': 'userType error',
            }
            logger_request.info(data)
            return JsonResponse(data)                   
    
    elif requestParam['operation'] == '1': 
        question.isActive = False
        question.save()
        option = '删除了' + str(question.title) + '问题'
        userIP = datacheck.getIP(request)
        log = UserLog.objects.create(
            user=user,
            userIP=userIP,
            operate=option,
        )
    
    elif requestParam['operation'] == '2' and question.isActive == False : 
        question.isActive = True
        question.save() 
        option = '恢复了' + str(question.title) + '问题'
        userIP = datacheck.getIP(request)
        log = UserLog.objects.create(
            user=user,
            userIP=userIP,
            operate=option,
        )               
    
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)